package com.dc.base.network;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author 冰柠檬dc
 */
public class NetworkApi {

    private static OkHttpClient okHttpClient;

    private static String mBaseUrl;

    private static final HashMap<String, Retrofit> RETROFIT_HASHMAP = new HashMap<>();

    public static <T> T createService(Class<T> serviceClass, String baseUrl) {
        mBaseUrl = baseUrl;
        return getRetrofit(serviceClass).create(serviceClass);
    }

    private static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS);
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(interceptor);
            okHttpClient = builder.build();
        }
        return okHttpClient;
    }

    private static Retrofit getRetrofit(Class<?> serviceClass) {
        if (RETROFIT_HASHMAP.get(mBaseUrl + serviceClass.getName()) != null) {
            return RETROFIT_HASHMAP.get(mBaseUrl + serviceClass.getName());
        }
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(mBaseUrl)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        RETROFIT_HASHMAP.put(mBaseUrl + serviceClass.getName(), retrofit);
        return retrofit;
    }
}
